﻿using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

namespace JJYYCore.UIComponents.Slide
{
    public class EmptySlideUI : MonoBehaviour
    {
        [Header("BasicGroup")]
        [SerializeField]
        private HorizontalLayoutGroup layoutGroup;
        [SerializeField]
        private int defaultIndex = 0;

        private int activeIndex;
        private Vector3 center, childSize;

        public UnityAction<int> moveToIndexAction;

        void Awake()
        {
            moveToIndexAction += (int value) => { };
            SetOffsetProperties();
        }


        public void MoveTo(int index)
        {
            index = Mathf.Min(Mathf.Max(index, 0), layoutGroup.transform.childCount - 1);

            var xOffset = childSize;
            xOffset.y = 0;

            var targetPos = center - xOffset * index;
            layoutGroup.transform.position = targetPos;

            moveToIndexAction(index);
        }

        private void SetOffsetProperties()
        {
            if (!CheckOffsetNodesSize())
            {
                Debug.LogError("HorLayout检测初始化并未通过!初始化失败");
                return;
            }

            SetOffsetData();
            MoveTo(activeIndex);
        }

        private bool CheckOffsetNodesSize()
        {
            Vector2 lastSize = Vector2.zero;

            for (int i = 0; i < layoutGroup.transform.childCount; i++)
            {
                var child = layoutGroup.transform.GetChild(i).GetComponent<RectTransform>();

                if (lastSize != Vector2.zero && lastSize != child.sizeDelta)
                {
                    Debug.LogError("子对象尺寸并不相同,当前激活的尺寸为:" + child.sizeDelta + ",上一次激活的尺寸为:" + lastSize);
                    Debug.LogError("当前对象名称为:" + child.name);
                    return false;
                }

                lastSize = child.sizeDelta;
            }

            return true;
        }

        private void SetOffsetData()
        {
            center = layoutGroup.transform.position;
            childSize = layoutGroup.transform.GetChild(0).GetComponent<RectTransform>().sizeDelta;
            activeIndex = defaultIndex;
        }
    }
}